package com.dbflow5.processor.definition;

import com.dbflow5.StringUtils;
import com.dbflow5.annotation.ConflictAction;
import com.dbflow5.annotation.UniqueGroup;
import com.dbflow5.processor.definition.column.ColumnDefinition;
import com.dbflow5.processor.definition.column.ReferenceColumnDefinition;
import com.squareup.javapoet.CodeBlock;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 */
public class UniqueGroupsDefinition {

    public List<ColumnDefinition> columnDefinitionList = new ArrayList<>();
    public int number;

    private final ConflictAction uniqueConflict;

    public UniqueGroupsDefinition(UniqueGroup uniqueGroup) {
        number = uniqueGroup.groupNumber();
        uniqueConflict = uniqueGroup.uniqueConflict();
    }

    public void addColumnDefinition(ColumnDefinition columnDefinition) {
        columnDefinitionList.add(columnDefinition);
    }

    public CodeBlock creationName() {
        CodeBlock.Builder codeBuilder = CodeBlock.builder().add(", UNIQUE(");
        codeBuilder.add(StringUtils.joinToString(columnDefinitionList, ", ", columnDefinition -> {
            if (columnDefinition instanceof ReferenceColumnDefinition) {
                return StringUtils.joinToString(((ReferenceColumnDefinition) columnDefinition).referenceDefinitionList(), ", ", it -> StringUtils.quote(it.columnName()));
            } else {
                return StringUtils.quote(columnDefinition.columnName);
            }
        }));
        codeBuilder.add(") ON CONFLICT $L", uniqueConflict);
        return codeBuilder.build();
    }
}